package com.apexedu.portal.service.impl;

import com.apexedu.biz.Const;
import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.action.IdLoginAction;
import com.apexedu.portal.action.AppSetAction;
import com.apexedu.portal.entity.AppFunctionConfig;
import com.apexedu.portal.entity.AppRoleFunction;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.json.JsonUtil;
import net.ysen.tree.entitybean.TreeNode;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by janabo on 2014-12-5.
 */

@Service("appSetService")
public class AppSetServiceImpl extends AbstractBaseServiceSupport {

    @Override
    public void saveOrUpdate(Object myaction) throws Exception {
        AppSetAction action = (AppSetAction) myaction;
        AppFunctionConfig afc = action.getAppFunctionConfig();
        if (afc != null) {
            if (StringUtil.isNotBlank(afc.getId())) {
                baseDao.updateNotNull(afc);
                BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_APP_FUNCTION_CONFIG, Const.LOG_ACTION_UPDATE,
                        IdLoginAction.getIpAddr(action.getRequest()));
            } else {
                afc.setId(SeqFactory.getNewSequenceAlone());
                if(StringUtil.isBlank(afc.getSuperid())){
                    afc.setSuperid("0");
                }
                baseDao.save(afc);
                BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_APP_FUNCTION_CONFIG, Const.LOG_ACTION_SAVE,
                        IdLoginAction.getIpAddr(action.getRequest()));
            }
        }
        //图标库集合
        List<String> listIcon = new ArrayList<String>();
        File file = new File(action.getSession().getServletContext().getRealPath("/") + "resources"  + File.separator + "appicons");
        for (File f : file.listFiles()) {
            listIcon.add(f.getName());
        }
        action.setListIcon(listIcon);
    }

    @Override
    public void load(Object myaction) throws Exception {
        AppSetAction action = (AppSetAction) myaction;
        String wid = action.getWid();
        AppFunctionConfig afc = DBUtil.queryBean("select * from APP_FUNCTION_CONFIG tb where tb.id = ?",AppFunctionConfig.class,wid);
        action.setAppFunctionConfig(afc);

        //图标库集合
        List<String> listIcon = new ArrayList<String>();
        File file = new File(action.getSession().getServletContext().getRealPath("/") + "resources" + File.separator + "appicons");
        for (File f : file.listFiles()) {
            listIcon.add(f.getName());
        }
        action.setListIcon(listIcon);
    }

    @Override
    public List<AppFunctionConfig> list(Object o, Pager pager) throws Exception {
        List<AppFunctionConfig> list = DBUtil.queryAllBeanList("select * from APP_FUNCTION_CONFIG t order by  style,orderno asc",AppFunctionConfig.class);
        return list;
    }

    @Override
    public boolean remove(Object myaction) throws Exception {
        AppSetAction action = (AppSetAction) myaction;
        String ids = action.getWid();
        boolean deleteSuccess = getBaseDao().deleteAll("AppFunctionConfig", "id", "=", ids);
        if(deleteSuccess)
            BusinessLogUtil.log(action.getUserloginid(), Const.CZDX_APP_FUNCTION_CONFIG, Const.LOG_ACTION_DEL,
                    IdLoginAction.getIpAddr(action.getRequest()));
        return deleteSuccess;
    }

    @Override
    public void openCreate(Object myaction) throws Exception {
        AppSetAction action = (AppSetAction) myaction;
        List<String> listIcon = new ArrayList<String>();
        File file = new File(action.getRequest().getRealPath("") + "\\resources\\appicons");
        for (File f : file.listFiles()) {
            listIcon.add(f.getName());
        }
        action.setListIcon(listIcon);
    }

    public String getMenus() throws Exception {
       String regSql = "select t.appid as id,t.appname as text,'' as parentid from t_access_app_reg t where t.state='1' order by t.ordernum desc";
       String roleSql = "select s.roleid as id, to_char(s.rolename) as text,s.belongtoapp as parentid from T_SYS_ROLE s where s.state='1' and exists" +
               " (select 1 from t_access_app_reg b where s.belongtoapp = b.appid and b.state='1') ";
        List<TreeNode> reglist = DBUtil.queryAllBeanList(regSql, TreeNode.class);
        List<TreeNode> rolelist = DBUtil.queryAllBeanList(roleSql, TreeNode.class);
        List<TreeNode> list = new ArrayList<TreeNode>();
        list.addAll(reglist);
        list.addAll(rolelist);
        String jsonStr = JsonUtil.getJSONString(list);
        return jsonStr;
    }

    /**
     * 添加app菜单对应的角色权限
     * @param menuids 角色id
     * @param appid 菜单id
     * @throws Exception
     */
    public void saveBatchService(String menuids,String appid) throws Exception {
        if(StringUtils.isNotBlank(menuids)){
             String[] ids =  menuids.split(",");
            String sql = "delete from APP_ROLE_FUNCTION t where t.functionid = ? ";
            DBUtil.executeSQL(sql,appid);//删除原有的
            List<AppRoleFunction> list = new ArrayList<AppRoleFunction>();
            for (int j = 0; j < ids.length; j++) {
                AppRoleFunction arf = new AppRoleFunction();
                arf.setWid(SeqFactory.getNewSequenceAlone());
                arf.setRoleid(ids[j]);
                arf.setFunctionid(appid);
                list.add(arf);
            }
            getBaseDao().saveAll(list);
        }
    }

    /**
     * 查询app选项卡菜单已存在的角色
     * @param appid
     * @return
     */
    public String getCheckedRole(String appid){
        List<AppRoleFunction> list = DBUtil.queryAllBeanList("select a.roleid from APP_ROLE_FUNCTION a where a.functionid = ?",AppRoleFunction.class,appid);
        String ids="";
        int i = 0;
        for(AppRoleFunction a : list){
            i++;
            if(i == list.size()){
                ids += a.getRoleid();
            }else{
                ids += a.getRoleid()+",";
            }
        }
        return ids;
    }
}
